package com.sm.appbase.base.basemvp;

import android.text.TextUtils;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sm.appbase.base.BaseFragment;
import com.sm.appbase.net.exception.NetErrorException;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * @author azheng
 * @date 2018/4/24.
 * GitHub：https://github.com/RookieExaminer
 * Email：wei.azheng@foxmail.com
 * Description：
 */
public abstract class BaseMvpFragment<T extends BasePresenter> extends BaseFragment implements BaseView {

    protected T mPresenter;
    private CompositeDisposable mCompositeDisposable;
    SpotsDialog spotsDialog;

    public String getTitle() {
        return "";
    }


    @Override
    protected void initData() {
        super.initData();
        mCompositeDisposable = new CompositeDisposable();
    }

    @Override
    public void onDestroyView() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear(); // clear时网络请求会随即cancel
            mCompositeDisposable = null;
        }
        super.onDestroyView();
    }

    @Override
    public void showLoading(String title) {
        if (spotsDialog == null) {
            spotsDialog = new SpotsDialog(mContext, title);
        }
        if (!TextUtils.isEmpty(title)) {
            spotsDialog.setText(title);
        } else {
            spotsDialog.setText("");
        }
        if (!spotsDialog.isShowing()) {
            spotsDialog.show();
        }
    }

    @Override
    public void showLoading() {
        showLoading(null);
    }
    @Override
    public void hideLoading() {
        if (spotsDialog != null && spotsDialog.isShowing()) {
            spotsDialog.dismiss();
        }
        if (smartRefreshLayout != null) {
            smartRefreshLayout.finishRefresh();
            smartRefreshLayout.finishLoadMore();
        }
    }

    SmartRefreshLayout smartRefreshLayout;

    public void registFinishLoad(SmartRefreshLayout smartRefreshLayout) {
        this.smartRefreshLayout = smartRefreshLayout;
//        smartRefreshLayout.setEnableLoadMore(false);
    }

    @Override
    public void onError(NetErrorException throwable) {

    }


    @Override
    public void bindDispos(Disposable disposable) {
        if (mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
            mCompositeDisposable.add(disposable);
        }
    }


    @Override
    public void toast(String msg) {
        if (!TextUtils.isEmpty(msg))
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();

    }


}
